package com.jh.paymentchannel.qctpos.util;

import com.jh.paymentchannel.qctpos.pojo.request.QctposBaseRequest;
import com.jh.paymentchannel.qctpos.pojo.response.QctposBaseResponse;
import com.jh.paymentchannel.util.MD5;

import java.lang.reflect.Field;
import java.util.*;

public class QctposBaseUtils {


    public static List getCallList(){
         List<String> list = new ArrayList<String>();
         list.add("charset");
         return list;
    }
    public static List getVerifyList(){
         List<String> list = new ArrayList<String>();
         list.add("sign");
         return list;
    }

    public static TreeMap<String ,Object> objToTreeMap(Object obj, List list){
        TreeMap<String,Object> treeMap = new TreeMap<String, Object>();
        Field[] fields = obj.getClass().getDeclaredFields();
        Class superClass = obj.getClass().getSuperclass();
        Field[] fields1 = superClass.getDeclaredFields();
        add(treeMap,fields1,obj,list);
        add(treeMap,fields,obj,list);
        return treeMap;
    }

    private static TreeMap<String ,Object> add(TreeMap<String,Object> map ,Field[] fields,Object obj,List removeList){
        for(Field field:fields){
            field.setAccessible(true);
            try {
                String name =field.getName();
                if (removeList != null &&!removeList.contains(name)){
                    map.put(name, field.get(obj));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                continue;
            }
        }
        return map;
    }

    public static String signString(TreeMap<String,Object> map,String key){
        StringBuffer buf = new StringBuffer();
        for (String str : map.keySet()) {
            buf.append(str).append("=").append((String) map.get(str)).append("&");
        }
        String signData = buf.append("key=").append(key).toString();
        return MD5.MD5Encode(signData).toUpperCase();
    }

    public static String sign(QctposBaseRequest qctposBaseRequest,List list,String key){
        return signString(objToTreeMap(qctposBaseRequest,list),key);
    }


 //   public static void main(String[] args) {
//        TreeMap<String,Object> treeMap = objToTreeMap(new QctposPayRequest());
//        for (String  s : treeMap.keySet()){
//            System.out.println(s);
//        }
   // }
}
